package com.banhujiu.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * @author banhujiu
 * @date 2018/4/5 0005 14:48
 */
public class BatchOperation {
	public static <T, E> E batchOperation(Integer batchSize, List<T> list, Function<List<T>, E> function, BiFunction<E, E, E> biFunction) {
		batchSize = batchSize == null ? 500 : batchSize;
		List<T> operationList = new ArrayList<>();
		int count = 0;
		E result = null;
		for (int i = 0; i < list.size(); i++) {
			operationList.add(list.get(i));
			if ((list.size() - 1) == i || count >= batchSize) {
				E e = function.apply(operationList);
				if (result == null) {
					result = e;
				} else {
					result = biFunction.apply(result, e);
				}
				count = 0;
				operationList.clear();
			}
			count++;
		}
		return result;
	}


	public static <T> Integer batchOperation(Integer batchSize, List<T> list, Function<List<T>, Integer> function) {
		return batchOperation(batchSize, list, function, (a, b) -> a + b);
	}
}
